import { BASE_URL } from './ip'
import Vue from 'vue'

/**
 * code状态
 */
function _modalCode(data) {
  if (!data || !data.code) return
  switch (Number(data.code)) {
    case -1:
      let title = ''
      if(data?.data.length > 30 || !data.data ){
        title = '请求错误'
      } else {
        title = data.data
      }
      uni.showToast({ title: title, icon: 'none' })
      break;
    case 403:
      uni.showToast({ title: '未登录', icon: 'none' })
      const pages = getCurrentPages()
      if (pages.length && pages[pages.length - 1].route !== 'pages/login/index') {
        setTimeout(() => {
          // 退出
          uni.reLaunch({
            url: '/pages/login/index'
          })
        }, 500)
      }
      break;
    case 404:
      uni.showToast({ title: '请求的资源无法找到！', icon: 'none' })
      break;
    case 500:
      uni.showToast({ title: '请求无法完成，服务器内部错误！', icon: 'none' })
      break;
    case 503:
      uni.showToast({ title: '请求服务器正忙，请稍后再试！', icon: 'none' })
      break;
    default:
      break;
  }
}

const Plugin = {}
class Loading {
  constructor() {
    this.loading = false
    this.timer = null

    this.noLoadingUrl = [
      '/personnel/clientId/saveOrUpdate',
      '/mobile/version',
      '/alarm/fusionAnalysis/getHistoryRealTimePushCurve'
    ]
  }
  show(url) {
    if (this.loading === false && this.noLoadingUrl.includes(url) === false) {
      this.loading = true
      uni.showLoading({ title: '加载中...' })

      this.timer = setTimeout(() => {
        if (this.loading) {
          this.loading = false
          uni.hideLoading()
          uni.showToast({ title: '网络超时，请稍后再试！', icon: 'none' })
        }
      }, 60000)
    }
  }
  hide() {
    if (this.loading) {
      uni.hideLoading()
      setTimeout(() => {
        this.loading = false
        clearTimeout(this.timer)
      }, 500)
    }
  }
}

const loading = new Loading()

const httpConfig = new Map()
httpConfig.set('$get', {
  method: 'GET',
  header: {
    'content-Type': 'application/json',
  }
}).set('$post', {
  method: 'POST',
  header: {
    'content-Type': 'application/json',
  }
}).set('$form', {
  method: 'POST',
  header: {
    'content-Type': 'application/x-www-form-urlencoded',
  }
})

Plugin.install = function(Vue) {
  httpConfig.forEach((value, key, map) => {
    Reflect.defineProperty(Vue.prototype, key, {
      value: (url, data) => {
        return new Promise((resolve, reject) => {
          loading.show(url)
          uni.request({
            url: BASE_URL + url,
            method: value.method,
            sslVerify: false,
            header: {
              'X-Token': getApp().globalData.token || '',
              ...value.header
            },
            data: data,
            success: (res) => {
              _modalCode(res.data)
              resolve(res.data)
            },
            fail: (err) => {
              uni.showToast({ title: err, icon: 'none', duration: 1000 })
              reject(err)
            },
            complete: () => {
              loading.hide()
            }
          })
        })
      }
    })
  })
}

Vue.use(Plugin)

export default Plugin
